import 'package:enterprise_v6_app/app/components/custom_refresh.dart';
import 'package:enterprise_v6_app/app/components/department_regional_organization_tree/regional_organization_tree_view.dart';
import 'package:enterprise_v6_app/app/components/special_operation/custom_select_function.dart';
import 'package:enterprise_v6_app/app/components/toast_widget.dart';
import 'package:enterprise_v6_app/app/core/constans/dict_data_info.dart';
import 'package:enterprise_v6_app/app/core/core.dart';
import 'package:enterprise_v6_app/app/core/ext/ext.dart';
import 'package:enterprise_v6_app/app/core/http/http.dart';
import 'package:enterprise_v6_app/app/core/utils/customEndDrawer.dart';
import 'package:enterprise_v6_app/app/core/utils/interface.dart';
import 'package:enterprise_v6_app/app/data/entities/application/get_dict_all_entity.dart';
import 'package:enterprise_v6_app/app/data/entities/common/department_user_tree_entity.dart';
import 'package:enterprise_v6_app/app/data/entities/double_control/get_target_tasking_entity.dart';
import 'package:enterprise_v6_app/app/modules/application/double_prevention_page/danger_investigation_page/danger_investigation_controller.dart';
import 'package:enterprise_v6_app/router/app_pages.dart';

///任务分配已分配
class TaskAssignedController extends GetxController {
  /// 选中的节点
  DepartmentUserTreeEntity selectedEntity = DepartmentUserTreeEntity();

  /// 列表刷新key
  final GlobalKey<CustomEasyRefreshListState> globalKey = GlobalKey();

  /// 筛选右侧栏控制Key
  final riskRightScaffoldKey = GlobalKey<ScaffoldState>();

  ///部门id (获取部门及人员树->)筛选后传入的id 46f265fd-0722-47eb-8728-ddf714b5d6ae
  String? departmentNameId = '';

  RxString workKindNameBack = '请选择'.obs;
  String? workKind = '';

  /// 搜索字符串
  String? searchX = '';

  /// 查看已分配任务列表
  Future<List<GetTargetTaskingEntity>> getTargetTaskingAPP(int index, int size, {String? search}) async {
    final res = await HttpUtil().generateGetRequest<List<GetTargetTaskingEntity>>(
      Interface.getTargetTasking,
      queryParameters: {
        'id': departmentNameId,
        'workKind': workKind,
        'troubleshootContent': searchX,
        'pageNum': index,
        'pageSize': 5,
      },
    ).execute();
    List<GetTargetTaskingEntity>? list = [];
    res.onSuccess((result) {
      if (result.data != null) {
        list = result.data;
      }
    });
    return list ?? [];
  }

  ///筛选按钮
  void onFilterButtonPressed() {
    final DangerInvestigationController controller = Get.find<DangerInvestigationController>();
    controller.filterWidget.value = _filterWidget();
    controller.riskRightScaffoldKey.currentState?.openEndDrawer();
    // riskRightScaffoldKey.currentState?.openEndDrawer();
  }

  ///详情
  void onClickDetail(String? id) {
    Get.toNamed(AppRoutes.allocationDetailsTwoPage, arguments: id);
  }

  ///移除已分配任务
  void delAllocationBaseMeasures(
    String? id,
  ) async {
    final res = await HttpUtil().generatePostRequest(
      Interface.delAllocationBaseMeasures,
      data: [id],
    ).execute();
    res.onSuccess((result) {
      AppToast.show('删除成功');
      globalKey.currentState?.onRefresh();
    });
    res.onError((result) {
      AppToast.showError('删除失败');
    });
  }

  /// 搜索
  void refreshPage() {
    globalKey.currentState?.onRefresh();
  }

  /// 重置
  void reset() {
    departmentNameId = '';
    workKind = '';
    workKindNameBack.value = '请选择';
    Get.find<DangerInvestigationController>().riskRightScaffoldKey.currentState?.closeEndDrawer();
    selectedEntity = DepartmentUserTreeEntity();
    globalKey.currentState!.onRefresh();
    update();
  }

  /// 确定
  void confirm() {
    Get.back();
    departmentNameId = selectedEntity.id;
    globalKey.currentState!.onRefresh();
    update();
  }

  GetDictAllEntity? dictEntity2;

  // bool isFirst = true;

  /// 任务类别
  void selectHiddenDangerInvestigationTaskWorkKindType() async {
    final List<GetDictAllEntity> dictList = await DictDataInfo.getDictionaryDataByTree(dictionaryType: 'hidden_danger_investigation_task_work_kind');
    CustomSelectFunction.selectMultipleBottomSheet<GetDictAllEntity>(
      title: '任务类别',
      dataList: dictList,
      checkedList: [dictEntity2 ?? GetDictAllEntity()],
      isMultiple: false,
      onCallBack: (value) {
        dictEntity2 = value[0];
        workKind = value[0].getId();
        workKindNameBack.value = value[0].getShowName().isEmpty ? '请选择' : value[0].getShowName();
      },
    );
  }

  Widget _filterWidget() {
    return CustomEndDrawer(
      centerContext: Column(
        children: [
          Obx(
            () => _selectType('任务类别', workKindNameBack.value),
          ),
          DepartmentRegionalOrganizationTreePage(
            selectedEntity: selectedEntity,
            onCallBack: (DepartmentUserTreeEntity entity) {
              selectedEntity = entity;
            },
          ),
        ],
      ),
      reset: reset,
      confirm: confirm,
    );
  }

  Widget _selectType(String firstName, String name) {
    return Column(
      children: [
        _alignTitle(firstName),
        AppGaps.vGap16,
        Container(
          height: 38.w,
          decoration: BoxDecoration(
            color: Colors.white,
            borderRadius: BorderRadius.circular(8),
            border: Border.all(width: 1.w, color: const Color(0xFFE3E7EE)),
          ),
          child: Row(
            children: [
              AppGaps.hGap20,
              Expanded(
                child: Text(
                  name,
                  style: TextStyle(
                    fontSize: 12.sp,
                    color: const Color(0xFF495061),
                    fontWeight: FontWeight.w400,
                  ),
                ),
              ),
              SvgPicture.asset(AppImages.icon_filter_right_arrow),
              AppGaps.hGap20,
            ],
          ),
        ).clickOnce(() {
          if (firstName == '任务类别') {
            selectHiddenDangerInvestigationTaskWorkKindType();
          }
        }),
        AppGaps.vGap16,
      ],
    );
  }

  Widget _alignTitle(String title) {
    return Align(
      alignment: Alignment.centerLeft,
      child: Text(
        title,
        style: TextStyle(
          fontSize: 14.sp,
          fontWeight: FontWeight.w500,
        ),
      ),
    );
  }
}
